package main

import (
	"context"
	"log"
	"os/exec"
	"time"
)

type result struct {
	err    error
	output []byte
}

func main() {
	var (
		ctx        context.Context
		cancelFunc context.CancelFunc
		cmd        *exec.Cmd
		resultChan chan *result
		res        *result
	)

	resultChan = make(chan *result, 1000)
	ctx, cancelFunc = context.WithCancel(context.TODO())
	go func() {
		var (
			output []byte
			err    error
		)
		cmd = exec.CommandContext(ctx, "powershell", "Start-Sleep -s 3; echo 123")
		output, err = cmd.CombinedOutput()
		log.Println(string(output))
		// 把任务结果传给main协程
		resultChan <- &result{
			err,
			output,
		}
	}()
	time.Sleep(1 * time.Second)
	// 取消上下文
	cancelFunc()
	// 取出执行结果
	res = <-resultChan
	log.Println(res.err, string(res.output))
}
